< previous page page_619 next page >

Page 619
Changing the Record Source from Code
As you have just seen, you can easily set up the Data control while in design mode. However, even in the simplest project, you usually need to use the Data control in a more dynamic fashion. Fortunately, you can set it up from code by following a few simple steps:
1. Set the ConnectionString property.
2. Set the CommandType and RecordSource properties.
3. Execute the Refresh method of the ADO Data control to retrieve the data.
As it is now, the ADO Data control in the sample application retrieves every record in the Publishers table. However, you can easily add code that changes the RecordSource property so that a new recordset is displayed.
Suppose, for example, you want to display only information on publishers whose address is in a certain state. You can write a simple SQL query to display these addresses, as in the following example:
Select * from Publishers where State='NY'
Rather than set up the query at designtime, though, add some code to the sample project so that it can occur during program execution. First, add a command button to the form. Change the caption to State Lookup and the name of the command button to cmdState. Place the following lines of code in the Click event of cmdState:
    Dim sState As String
    Dim sSQL As String

    'BUILD SQL QUERY
    sSQL = "Select * from Publishers"
    sState = InputBox$("Enter State abbreviation:")
    If sState <> "" Then sSQL = sSQL & " WHERE State ='" & sState & "'"

    'UPDATE THE ADO DATA CONTROL
    Adodc1.CommandType = adCmdText
    Adodc1.RecordSource = sSQL
    Adodc1.Refresh
Run the sample project again, and click the button. Enter NY and available records should change to include only those publishers in New York. You can verify this information by clicking the navigation buttons on the ADO Data control.
Using the DataGrid Control
Much of the information that computer programs deal with is presented in the form of a grid of columns and rows, like you would find on a spreadsheet. In fact, for many people, and many types of data, this "grid" is the preferred method of viewing information. The DataGrid control, a new control in Visual Basic 6.0, allows you to display data from a database in grid format. Depending on how the DataGrid is set up, the user can even edit the cells of the grid directly and change the underlying data.

 
< previous page page_619 next page >